package com.xgkj.diyiketang.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Pair;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.easeui.domain.EaseUser;
import com.easemob.easeui.ui.EaseConversationListFragment;
import com.easemob.util.NetUtils;
import com.xgkj.diyiketang.EatShowApp;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.activity.NewMessageReceive;
import com.xgkj.diyiketang.activity.ZhuBoGongGaoListActivity;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.hxsdk.DemoDBManager;
import com.xgkj.diyiketang.hxsdk.DemoHelper;
import com.xgkj.diyiketang.task.GetUserInfoTask;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.BaseActivity;
import com.xgkj.diyiketang.activity.ChatActivity;
import com.xgkj.diyiketang.activity.MainActivity;
import com.xgkj.diyiketang.activity.SysMsgListActivity;
import com.xgkj.diyiketang.hxsdk.InviteMessgeDao;
import com.xgkj.diyiketang.util.PalLog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;

/**
 * Created by Administrater on 2015/12/8.
 */
public class MessageFragment extends EaseConversationListFragment {
    private final String TAG = getClass().getSimpleName();

    private TextView errorText;
    private RelativeLayout msgLayout;
    private RelativeLayout gonggaoLayout;
    private Context mContext;
    private WeiduXXReceive weiduReceiver;

    @Override
    protected void initView() {
        mContext = getActivity();
        super.initView();
        if(weiduReceiver==null){
            weiduReceiver = new WeiduXXReceive();
            IntentFilter messageFilter = new IntentFilter(VideoFragment.WEIDUMESSAGE_ACTION);
            messageFilter.addAction(NewMessageReceive.NEWMESSAGE_REFRESH_ACTION);
            mContext.registerReceiver(weiduReceiver,messageFilter);
        }
        View errorView = (LinearLayout) View.inflate(getActivity(),R.layout.em_chat_neterror_item, null);
        errorItemContainer.addView(errorView);
        errorText = (TextView) errorView.findViewById(R.id.tv_connect_errormsg);
        msgLayout = (RelativeLayout) getView().findViewById(R.id.sys_layout);
        msgLayout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), SysMsgListActivity.class);
                startActivity(intent);
            }
        });

        gonggaoLayout= (RelativeLayout) getView().findViewById(R.id.zhubogonggao);
        gonggaoLayout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ZhuBoGongGaoListActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
//            PalLog.e("刷新界面","dfalsj");
//            EMChatManager.getInstance().loadAllConversations();
            refresh();
        }
    }

    private List<EMConversation> list;
    @Override
    protected void setUpView() {
        super.setUpView();
        // 注册上下文菜单
        list = loadConversationList();
        for (EMConversation em : list){
            EaseUser user = DemoDBManager.getInstance().getUser(em.getUserName());
            if (user.getNick()==null || user.getAvatar() == null){
                doGetUserInfo(em.getUserName());
            }
        }
        registerForContextMenu(conversationListView);
        conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EMConversation conversation = conversationListView.getItem(position);
                String username = conversation.getUserName();
                String nick = EatShowApp.getInstance().getmUserInfo().getNickName();
                if (username.equals(EMChatManager.getInstance().getCurrentUser()))
                    Toast.makeText(getActivity(), R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
                else {
                    // 进入聊天页面
                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    if(conversation.isGroup()){
                        if(conversation.getType() == EMConversation.EMConversationType.ChatRoom){
                            // it's group chat
                            intent.putExtra(ProtocolConst.EXTRA_CHAT_TYPE, ProtocolConst.CHATTYPE_CHATROOM);
                        }else{
                            intent.putExtra(ProtocolConst.EXTRA_CHAT_TYPE, ProtocolConst.CHATTYPE_GROUP);
                        }

                    }
                    // it's single chat
                    intent.putExtra(ProtocolConst.EXTRA_USER_ID, username);
                    //intent.putExtra("NICKNAME",nick);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    protected void onConnectionDisconnected() {
        super.onConnectionDisconnected();
        if (NetUtils.hasNetwork(getActivity())){
            errorText.setText(R.string.can_not_connect_chat_server_connection);
        } else {
            errorText.setText(R.string.the_current_network);
        }
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        getActivity().getMenuInflater().inflate(R.menu.em_delete_message, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        boolean handled = false;
        boolean deleteMessage = false;
        /*if (item.getItemId() == R.id.delete_message) {
            deleteMessage = true;
            handled = true;
        } else*/ if (item.getItemId() == R.id.delete_conversation) {
            deleteMessage = true;
            handled = true;
        }
        EMConversation tobeDeleteCons = conversationListView.getItem(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position);
        // 删除此会话
        EMChatManager.getInstance().deleteConversation(tobeDeleteCons.getUserName(), tobeDeleteCons.isGroup(), deleteMessage);
        InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(getActivity());
        inviteMessgeDao.deleteMessage(tobeDeleteCons.getUserName());
        refresh();

//        // 更新消息未读数
//        ((MainActivity) getActivity()).updateUnreadLabel();

        return handled ? true : super.onContextItemSelected(item);
    }

    protected List<EMConversation> loadConversationList(){
        // 获取所有会话，包括陌生人
        Hashtable<String, EMConversation> conversations = EMChatManager.getInstance().getAllConversations();
        // 过滤掉messages size为0的conversation
        /**
         * 如果在排序过程中有新消息收到，lastMsgTime会发生变化
         * 影响排序过程，Collection.sort会产生异常
         * 保证Conversation在Sort过程中最后一条消息的时间不变
         * 避免并发问题
         */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    //if(conversation.getType() != EMConversationType.ChatRoom){
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    //}
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }

    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    private void doGetUserInfo(final String from){
        GetUserInfoTask task = new GetUserInfoTask(from);
        task.addListener(new ShowToastTaskEventListener(mContext){
            @Override
            public void handleTaskCompleted(int taskId, int result, Object data) {
                super.handleTaskCompleted(taskId, result, data);
                if(data != null){
                    EatShowUserInfo info = (EatShowUserInfo) data;
                    if (info != null){
                        String nick = info.getNickName();
                        String userLogo = info.getUserLogo();
                        EaseUser user = new EaseUser(from);
                        user.setNick(nick);
                        user.setAvatar(userLogo);
                        EaseUser cacheUser = DemoDBManager.getInstance().getUser(from);
                        if(cacheUser != null && (!nick.equals(cacheUser.getNick()) || !userLogo.equals(cacheUser.getAvatar()))) {
                            DemoHelper.getInstance().saveContact(user);
                            PalLog.e(TAG, "聊天用户保存成功");
                            refresh();
                        }else{
                            PalLog.e(TAG,"用户已存在");
                        }
                    }
                }
            }

            @Override
            public void handleTaskError(int taskId, int errorCode, String errorMsg) {
                super.handleTaskError(taskId, errorCode, errorMsg);
            }
        });
        EatShowApp.getInstance().getTaskManager().addTask(task);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (weiduReceiver != null){
            mContext.unregisterReceiver(weiduReceiver);
            weiduReceiver = null;
        }
    }

    public class WeiduXXReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            refresh();
        }
    }



}
